package helper;

import com.zhangyx.crawler.comm.EncryptUtil;
import com.zhangyx.crawler.comm.ThreadUtil;
import com.zhangyx.crawler.core.HttpClientUtil;
import comm.CacheUtil;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.logging.log4j.util.Strings;
import org.apache.tomcat.util.security.MD5Encoder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

public class ApkPureHelper {

    /**
     *  apkNode
     * @param srcUrl
     * @return
     */
    public static String getDownLoadUrl(String srcUrl) {
        if (srcUrl == null) {
            return srcUrl;
        }
        String key = EncryptUtil.getMD5(srcUrl);
        String target = CacheUtil.getCache().getIfPresent(key);
        if (Strings.isNotBlank(target)) {
            return target;
        }
        HttpClientUtil httpClientUtil = HttpClientUtil.GET(srcUrl)
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36");
        httpClientUtil.start();
        String html = httpClientUtil.getHtml();
        if (Strings.isBlank(html)) {
            return srcUrl;
        }
        Document document = Jsoup.parse(html);
        if (document != null) {
            try {
                Elements elements = document.select("#download_link");
                if (elements != null && elements.size() == 1) {
                    target = elements.get(0).attr("href");
                    CacheUtil.getCache().put(key, target);
                }
            } catch (Exception e) {

            }
        }
        if (Strings.isBlank(target)) {
            target = srcUrl;
        }
        return target;
    }

    /**
     * 从apk.boboww.com:8080上获取可用的真实的下载链接
     * @return
     */
    public static String getUrlFromAPKNode(String srcUrl) {
        if (srcUrl == null) {
            return srcUrl;
        }
        HttpClientUtil httpClientUtil = HttpClientUtil.GET("http://apk.boboww.com:8080/apk/downUrl4node?srcUrl=" + srcUrl).start();
        return httpClientUtil.getHtml();
    }
    public static void main(String[] args) {
        System.out.println(getDownLoadUrl("https://m.apkpure.com/cn/google-chrome-fast-secure/com.android.chrome/download?from=details"));
        ThreadUtil.sleepMills(10000);
        System.out.println(getDownLoadUrl("https://m.apkpure.com/cn/google-chrome-fast-secure/com.android.chrome/download?from=details"));

    }
}
